//
//  MidFunc.m
//  简单的算法
//
//  Created by 崔博 on 2018/9/6.
//  Copyright © 2018年 崔博. All rights reserved.
//

#import "MidFunc.h"

@implementation MidFunc
// 二分法实现数组查找

// 递归算法
int recrbinary(int * a,int key ,int low, int high)
{
    int mid;
    if (low > high) {
        return - 1;
    }
    mid = (low + high) / 2;
    if (a[mid] == key) {
        return mid;
    }else if (a[mid] > key)
    {
        return recrbinary(a, key, low, mid - 1);
        
    }else
    {
        return recrbinary(a, key, mid + 1, high);
    }
}
// 非递归算法
int binary(int * a, int key, int n)
{
    int left = 0, right = n - 1, mid = 0;
    
    mid = (left + right) / 2;
    while (left < right && a[mid] != key) {
        if (a[mid] < key)
        {
            if (a[mid] < key) {
                left = mid + 1;
            }else if (a[mid] > key){
                right = mid - 1;
            }
            mid = (left + right) / 2;
        }
    }
    if (a[mid] == key) {
        return mid;
    }
    return -1;
}
@end
